// import path from 'path'
import fs from 'fs'
import xlsx from 'node-xlsx'
import { ipcMain } from 'electron'
import iconv from 'iconv-lite'
/**
 * 读取文件数据
 */
function readFileData(filePath) {
  return xlsx.parse(filePath)
}

/**
 * 写入文件
 * @param {*} key
 * @param {*} items
 * @param {*} desc
 */
function writeTextFile(outPath, items, desc, event) {
  let [first] = items
  var text = ''
  text += '[属性描述]\r\n'
  text += desc
  text += '[地块坐标]\r\n'

  // 生成头数据
  text += `${items.length + (!first.pointNum ? 1 : 0)},${first.area},${first.code},${first.town}${first.village},面,${first.mapNum},${first.landType},${first.landCode},@\r\n`
  // 生成坐标数据
  let points = items.map((value, index) => {
    return `${(value.pointNum) || ('J' + (index + 1))},1,${value.x},${value.y}`
  })

  if (!first.pointNum) {
    // 生成回路数据
    points.push(`${first.pointNum || ('J1')},1,${first.x},${first.y}`)
  }

  text += points.join('\r\n')

  fs.writeFile(outPath, iconv.encode(text, 'gbk'), null, (err) => {
    if (err) throw err
    event.sender.send('writeFileDataSuccess', outPath)
  })
}

export function init() {
  console.log('mainWindow opened')

  ipcMain.on('readFileData', (event, filePath) => {
    let fileData = readFileData(filePath)
    event.sender.send('readFileDataSuccess', fileData)
  })

  ipcMain.on('writeFileData', (event, outPath, items, desc) => {
    writeTextFile(outPath, items, desc, event)
  })
}
